package org.ueg.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateDao<T> {
	private static Configuration configuration = null;
	private static ServiceRegistry serviceRegistry = null;
	private static SessionFactory sessionFactory = null;

	//@SuppressWarnings("rawtypes")
	private Class classe;

	//@SuppressWarnings("rawtypes")
	public HibernateDao(Class classe){
		this.classe = classe;
		if (configuration == null){
			configuration = new Configuration();
			configuration.configure();
		}
		if (serviceRegistry == null){
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		}
		if (sessionFactory == null) {
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		}		
	}
	//@SuppressWarnings("unchecked")
	protected T getById(Long id) throws Exception{
		Session session = getSession();
		try{
		return (T) session.get(classe, id);  
		}catch(Exception ex){
			throw ex;			
		}finally{
			session.close();
		}
	}
	//@SuppressWarnings("unchecked")
	protected List<T> listagem() throws Exception{
		Session session = getSession();
		try{
			Query query = session.createQuery("From " + classe);
			return query.list();
		}catch(Exception ex){
		throw ex;			
		}finally{
			session.close();
		}		
	}
	protected Session getSession() {
		return sessionFactory.openSession();
	}	
}